<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns="http://www.w3.org/1999/html">
<head>
    <th:block th:include="include :: header('百度ECharts')"/>
    <th:block th:include="include :: toastr-css"/>

    <style>
        .nowrap {
            white-space: nowrap; /* 禁止文本自动换行 */
            overflow: hidden; /* 隐藏超出的内容 */
            text-overflow: ellipsis; /* 显示为省略号 */
            max-width: 200px; /* 设置最大宽度 */
        }

        .scrollable-table-container {
            overflow-x: auto;
            white-space: nowrap;
        }
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight"
     style="padding-left: 8px !important; padding-right: 8px; !important">

    <div class="row">

        <!--支出-->
        <div class="col-sm-4">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="echarts" id="pay-line-chart"></div>
                </div>
            </div>
        </div>

        <!--收入-->
        <div class="col-sm-4">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="echarts" id="income-line-chart"></div>
                </div>
            </div>
        </div>

        <!--不计入-->
        <div class="col-sm-4">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="echarts" id="moneyIgnore-line-chart"></div>
                </div>
            </div>
        </div>

        <div class="ibox ">
            <div class="ibox-title">
                <h5>收入支出详情</h5>
            </div>
            <div class="ibox-content">

                <div>
                    本账单共支出 <strong class="text-danger"><span th:text="${totalPay}"></span></strong>，
                    收入 <strong class="text-success"><span th:text="${totalIncome}"></span></strong>，
                    不计入 <strong class="text-warning"><span th:text="${totalIgnore}"></span></strong>
                </div>

                <hr/>

                <!--月账单-->
                <h5 th:text="'月账单 ' + '(' + ${accountName} + ')'">月账单</h5>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th style="text-align: center">日期</th>
                            <th style="text-align: center">支出</th>
                            <th style="text-align: center">收入</th>
                            <th style="text-align: center">不计入</th>
                            <th style="text-align: center">结余</th>
                        </tr>
                        </thead>

                        <tbody id="bill-month-tbody">
                            <!-- 数据将通过AJAX动态插入到这里 -->
                        </tbody>
                    </table>
                </div>

                </hr>


                <h5 th:text="'分类月账单 ' + '(' + ${accountName} + ')'">分类月账单</h5>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead id=classByMonthMoneyTitle>
                        <tr>
                        </tr>
                        </thead>
                        <tbody id=classByMonthMoneyData>
                        <tr align="center">
                        </tr>
                        </tbody>
                    </table>
                </div>

                </hr>

                <!--分类账单-->
                <h5 th:text="'分类年账单 ' + '(' + ${accountName} + ')'">分类年账单</h5>

                <div class="table-responsive">

                    <div>
                        <div class="panel-options">
                            <ul class="nav nav-tabs">
                                <li class="active"><a data-toggle="tab" href="#tab-pay"><img th:src="@{/img/支出.svg}"
                                                                                             alt="支出"
                                                                                             style="width: 24px; height: 24px;"></a>
                                </li>
                                </li>
                                <li class=""><a data-toggle="tab" href="#tab-income"><img th:src="@{/img/收入.svg}"
                                                                                          alt="收入"
                                                                                          style="width: 24px; height: 24px;"></a>
                                </li>
                                <li class=""><a data-toggle="tab" href="#tab-moneyIgnore"><img
                                        th:src="@{/img/不计入.svg}"
                                        alt="不统计"
                                        style="width: 24px; height: 24px;"></a>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <div class="panel-body">
                        <div class="tab-content">
                            <div id="tab-pay" class="tab-pane active">
                                <strong>支出</strong>
                                <div class="scrollable-table-container">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                        <tr>
                                            <th style="text-align: center">账单名称</th>
                                            <th style="text-align: center">类型</th>
                                            <th style="text-align: center">分类</th>
                                            <th style="text-align: center">金额</th>
                                            <th style="text-align: center; white-space: nowrap;">笔数</th>
                                        </tr>
                                        </thead>
                                        <tbody th:each="item,temp : ${accountClassList}">
                                        <tr align="center" th:if="${item.status == '2'}">
                                            <td style="white-space: nowrap;" th:text="${accountName}"></td>
                                            <td style="white-space: nowrap;" id="classTypeName" th:text="${item.classType}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.className}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.money}"></td>
                                            <td style="white-space: nowrap;white-space: nowrap;"th:text="${item.count}"></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div id="tab-income" class="tab-pane">
                                <strong>收入</strong>
                                <div class="scrollable-table-container">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                        <tr>
                                            <th style="text-align: center">账单名称</th>
                                            <th style="text-align: center">类型</th>
                                            <th style="text-align: center">分类</th>
                                            <th style="text-align: center">金额</th>
                                            <th style="text-align: center;white-space: nowrap;">笔数</th>
                                        </tr>
                                        </thead>
                                        <tbody th:each="item,temp : ${accountClassList}">
                                        <tr align="center" th:if="${item.status == '1'}">
                                            <td style="white-space: nowrap;" th:text="${accountName}"></td>
                                            <td style="white-space: nowrap;" id="classTypeName" th:text="${item.classType}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.className}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.money}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.count}"></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div id="tab-moneyIgnore" class="tab-pane">
                                <strong>不计入</strong>
                                <div class="scrollable-table-container">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                        <tr>
                                            <th style="text-align: center">账单名称</th>
                                            <th style="text-align: center">类型</th>
                                            <th style="text-align: center">分类</th>
                                            <th style="text-align: center">金额</th>
                                            <th style="text-align: center">笔数</th>
                                        </tr>
                                        </thead>
                                        <tbody th:each="item,temp : ${accountClassList}">
                                        <tr align="center" th:if="${item.status == '3'}">
                                            <td style="white-space: nowrap;" th:text="${accountName}"></td>
                                            <td style="white-space: nowrap;" id="classTypeName" th:text="${item.classType}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.className}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.money}"></td>
                                            <td style="white-space: nowrap;" th:text="${item.count}"></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>


            </div>
        </div>

        <!--近一年收支情况-->
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div style="height:600px" id="recent-line-chart"></div>
                </div>
            </div>
        </div>

    </div>

    <div class="ibox " >
        <div class="ibox-title">
            <h5 th:text="'支出前30排行榜 ' + '(' + ${accountName} + ')'">支出前30排行榜</h5>
        </div>
        <div class="ibox-content">
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                    <tr>
                        <th style="text-align: center">日期</th>
                        <th style="text-align: center">状态</th>
                        <th style="text-align: center">类型</th>
                        <th style="text-align: center">分类</th>
                        <th style="text-align: center">金额</th>
                        <th style="text-align: center">备注</th>
                    </tr>
                    </thead>
                    <tbody th:each="item,temp : ${payAccountAnalysisByMonthLastList}">
                    <tr align="center">
                        <td class="nowrap" th:text="${item.moneyDate}"></td>
                        <td class="nowrap" th:switch="${item.status}">
                            <span th:case="1">收入</span>
                            <span th:case="2">支出</span>
                            <span th:case="3">不计入</span>
                        </td>
                        <td style="white-space: nowrap;" id="classTypeName" th:text="${item.classType}"></td>
                        <td class="nowrap" th:text="${item.className}"></td>
                        <td class="nowrap" th:text="${item.money}"></td>
                        <td class="nowrap" align="left" th:text="${item.moneyIntroduce}"
                            th:title="${item.moneyIntroduce}"></td>
                    </tr>
                    </tbody>
                </table>
            </div>

        </div>
    </div>

</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: echarts-js"/>
<th:block th:include="include :: toastr-js"/>
<script type="text/javascript" th:inline="javascript">

    // 数据字典 (account_income_pay)
    var classTypeDatas = [[${@dict.getType('account_income_pay')}]];

    $.ajax({
        type: "get",
        url: "/account/bill/accountAnalysis/"+[[${accountId}]],
        dataType: "json",
        success: function (data) {
            // 支出图
            var payChart = echarts.init(document.getElementById("pay-line-chart"));
            var payOption = {
                title: {
                    text: [[${accountName}]] + ' 支出统计',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical', // 垂直方向布局
                    left: 'left',       // 左侧对齐
                    top: '1%',          // 距离顶部 1%
                    // 添加文本样式配置
                    textStyle: {
                        fontSize: 10   // 设置字体大小为 10px
                    }
                },
                series: [
                    {
                        name: '支出',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '15',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data:
                        data.accountClassPay

                    }
                ]
            };
            payChart.setOption(payOption);
            $(window).resize(payChart.resize);

            // 收入图
            var incomeChart = echarts.init(document.getElementById("income-line-chart"));
            var incomeOption = {
                title: {
                    text: [[${accountName}]] + ' 收入统计',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical', // 垂直方向布局
                    left: 'left',       // 左侧对齐
                    top: '1%',          // 距离顶部 1%
                    // 添加文本样式配置
                    textStyle: {
                        fontSize: 10   // 设置字体大小为 10px
                    }
                },
                series: [
                    {
                        name: '收入',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '15',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data:
                        data.accountClassIncome

                    }
                ]
            };
            incomeChart.setOption(incomeOption);
            $(window).resize(incomeChart.resize);

            // 不计入图
            var moneyIgnoreChart = echarts.init(document.getElementById("moneyIgnore-line-chart"));
            var moneyIgnoreOption = {
                title: {
                    text: [[${accountName}]] + ' 不计入统计',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical', // 垂直方向布局
                    left: 'left',       // 左侧对齐
                    top: '1%',          // 距离顶部 1%
                    // 添加文本样式配置
                    textStyle: {
                        fontSize: 10   // 设置字体大小为 10px
                    }
                },
                series: [
                    {
                        name: '不计入',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '15',
                                fontWeight: 'bold'
                            }
                        },

                        labelLine: {
                            show: false
                        },
                        data: data.accountClassMoneyIgnore
                    }
                ]
            };
            moneyIgnoreChart.setOption(moneyIgnoreOption);
            $(window).resize(moneyIgnoreChart.resize);

        }
    })

    $.ajax({
        type: "get",
        url: "/account/bill/accountAnalysisByMonth/" + [[${accountId}]],
        dataType: "json",
        success: function (data) {
            // 近期收支分析
            var pieChart = echarts.init(document.getElementById("recent-line-chart"));
            var pieoption = {
                title: {
                    text: '近一年分析',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'axis'
                },
                // 自定义线条颜色，所描绘的线条会在这里选颜色渲染
                color: ['green', 'red', 'yellow'],
                legend: {
                    data: ['收入', '支出', '不计入'],
                    top: '4%',
                },
                grid: {
                    left: '1%', // 调整左边距
                    right: '1%', // 调整右边距
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    axisLabel: {
                        interval: 0,//横轴信息全部显示
                        rotate: 45,//-30度角倾斜显示
                        fontSize: 10,// 字体大小
                    },
                    data: data.monthList
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '收入',
                        type: 'line',
                        lineStyle: {
                            color: 'green' // 设置线条颜色为绿色
                        },
                        data: data.incomeList
                    },
                    {
                        name: '支出',
                        type: 'line',
                        lineStyle: {
                            color: 'red' // 设置线条颜色为红色
                        },
                        data: data.payList
                    },
                    {
                        name: '不计入',
                        type: 'line',
                        lineStyle: {
                            color: 'yellow' // 设置线条颜色为黄色
                        },
                        data: data.moneyIgnoreList
                    }
                ]
            };
            pieChart.setOption(pieoption);
            $(window).resize(pieChart.resize);
        }
    })

    $.ajax({
        type: "post",
        url: "/account/bill/selectMoneyByClass",
        dataType: "json",
        cache: true,
        data: {"id": [[${accountId}]]},
        success: function (data) {

            // 一级表头
            var mapTitleOneList = data.data.mapTitleOneList;
            // 二级表头
            var mapTitleTwoList = data.data.mapTitleTwoList;
            // 表头
            var mapTitleList = data.data.mapTitleList;
            // 数据
            var mapDataList = data.data.mapDataList;

            // 生成表头
            var classByMonthMoneyTitleHtml = '';

            // 一级表头
            var classByMonthMoneyTitleHtml_ONE = '';
            mapTitleOneList.forEach(function (headerOne) {
                classByMonthMoneyTitleHtml_ONE += `<th colspan="${headerOne.colspan}" style="text-align: center;background-color: #d4d2d2;">${headerOne.title}</th>`;
            });
            classByMonthMoneyTitleHtml_ONE = '<tr>' + classByMonthMoneyTitleHtml_ONE + '</tr>';

            // 二级表头
            var classByMonthMoneyTitleHtml_TWO = '';
            mapTitleTwoList.forEach(function (headerTwo) {
                classByMonthMoneyTitleHtml_TWO += `<th colspan="${headerTwo.colspan}" style="text-align: center;background-color: #e0e0e0;">${$.table.selectDictLabel(classTypeDatas,headerTwo.title)}</th>`;
            });
            classByMonthMoneyTitleHtml_TWO = '<tr>' + classByMonthMoneyTitleHtml_TWO + '</tr>';

            // 三级表头
            var classByMonthMoneyTitleHtml_THREE = '';
            mapTitleList.forEach(function (header) {
                classByMonthMoneyTitleHtml_THREE += `<th style="text-align: center;">${header.title}</th>`;
            });
            classByMonthMoneyTitleHtml_THREE = '<tr>' + classByMonthMoneyTitleHtml_THREE + '</tr>';

            // 一级表头 + 二级表头 + 三级表头
            $('#classByMonthMoneyTitle').html(classByMonthMoneyTitleHtml_ONE + classByMonthMoneyTitleHtml_TWO + classByMonthMoneyTitleHtml_THREE);

            // 生成表格数据
            var classByMonthMoneyTitleData = '';
            mapDataList.forEach(function (item, index) {
                var isLastRow = index === mapDataList.length - 1; // 判断是否为最后一行
                var isSecondLastRow = index === mapDataList.length - 2;  // 判断是否为倒数第二行

                // 设置倒数第二行和最后一行的背景色
                var rowStyle = '';
                if (isLastRow) {
                    rowStyle = 'background-color: #90EE90;';  // 最后一行绿色
                } else if (isSecondLastRow) {
                    rowStyle = 'background-color: #f3f3b1;';  // 倒数第二行黄色
                }

                classByMonthMoneyTitleData += `<tr align="center" style="${rowStyle}">`;
                mapTitleList.forEach(function (header, index) {
                    classByMonthMoneyTitleData += `<td>${item[header.field]}</td>`;
                });
                classByMonthMoneyTitleData += '</tr>';
            });
            $('#classByMonthMoneyData').html(classByMonthMoneyTitleData);
        }
    });

    $.ajax({
        type: "post",
        url: "/account/bill/list",
        dataType: "json",
        data: {"accountId": [[${accountId}]],"pageNum":"1","pageSize":"20"},
        success: function(data) {

            const tbody = document.getElementById('bill-month-tbody');
            tbody.innerHTML = ''; // 清空现有内容

            console.log(data,"===>")
            // 当没有数据
            if (!data || !data.rows || data.rows.length == 0) {
                // 没有数据时，显示暂无数据
                const noDataRow = document.createElement('tr');
                const noDataCell = document.createElement('td');
                noDataCell.colSpan = 5; // 表格有5列
                noDataCell.style.fontWeight = 'bold'; // 加粗,行字体
                noDataCell.style.textAlign = 'center';
                noDataCell.style.paddingTop = '10px';
                noDataCell.style.paddingBottom = '10px';
                noDataCell.textContent = '暂无数据';
                noDataRow.appendChild(noDataCell);
                tbody.appendChild(noDataRow);
                return;
            }

            // 总计
            let totalPay = 0.00;
            let totalIncome = 0.00;
            let totalIgnore = 0.00;
            let totalBalance = 0.00;

            data.rows.forEach(item => {
                const row = document.createElement('tr');
                row.align = 'center';

                const dateCell = document.createElement('td');
                dateCell.textContent = item.month;
                row.appendChild(dateCell);

                const payCell = document.createElement('td');
                payCell.textContent = item.pay === 0.00 ? '-' : item.pay;
                row.appendChild(payCell);
                if (item.pay !== 0.00) {
                    totalPay += parseFloat(item.pay);
                }

                const incomeCell = document.createElement('td');
                incomeCell.textContent = item.income === 0.00 ? '-' : item.income;
                row.appendChild(incomeCell);
                if (item.income !== 0.00) {
                    totalIncome += parseFloat(item.income);
                }

                const ignoreCell = document.createElement('td');
                ignoreCell.textContent = item.moneyIgnore === 0.00 ? '-' : item.moneyIgnore;
                row.appendChild(ignoreCell);
                if (item.moneyIgnore !== 0.00) {
                    totalIgnore += parseFloat(item.moneyIgnore);
                }

                const balanceCell = document.createElement('td');
                balanceCell.textContent = item.balance === 0.00 ? '-' : item.balance;
                row.appendChild(balanceCell);
                if (item.balance !== 0.00) {
                    totalBalance += parseFloat(item.balance);
                }

                // 将行添加到表格中
                tbody.appendChild(row);
            });

            var rowsLength = data.rows.length;
            if (rowsLength>0){

                // 创建总计行
                const totalRow = document.createElement('tr');
                totalRow.style.fontWeight = 'bold'; // 加粗总计行字体
                totalRow.style.backgroundColor = '#f3f3b1'; // 设置黄

                const blankCell = document.createElement('td');
                blankCell.colSpan = 1; // 占据第一列
                blankCell.textContent = '总  计';
                blankCell.style.textAlign = 'center';
                totalRow.appendChild(blankCell);

                const totalPayCell = document.createElement('td');
                totalPayCell.textContent = totalPay.toFixed(2);
                totalPayCell.style.textAlign = 'center'; // 居中对齐
                totalRow.appendChild(totalPayCell);

                const totalIncomeCell = document.createElement('td');
                totalIncomeCell.textContent = totalIncome.toFixed(2);
                totalIncomeCell.style.textAlign = 'center'; // 居中对齐
                totalRow.appendChild(totalIncomeCell);

                const totalIgnoreCell = document.createElement('td');
                totalIgnoreCell.textContent = totalIgnore.toFixed(2);
                totalIgnoreCell.style.textAlign = 'center'; // 居中对齐
                totalRow.appendChild(totalIgnoreCell);

                const totalBalanceCell = document.createElement('td');
                totalBalanceCell.textContent = totalBalance.toFixed(2);
                totalBalanceCell.style.textAlign = 'center'; // 居中对齐
                totalRow.appendChild(totalBalanceCell);

                // 将总计行添加到表格中
                tbody.appendChild(totalRow);

                // 创建平均值行
                const avgRow = document.createElement('tr');
                avgRow.style.fontWeight = 'bold'; // 加粗平均值行字体
                avgRow.style.backgroundColor = '#90EE90'; // 设置黄


                const avgBlankCell = document.createElement('td');
                avgBlankCell.colSpan = 1; // 占据第一列
                avgBlankCell.textContent = '平均值';
                avgBlankCell.style.textAlign = 'center'; // 居中对齐
                avgRow.appendChild(avgBlankCell);

                const avgPayCell = document.createElement('td');
                avgPayCell.textContent = (totalPay / rowsLength).toFixed(2);
                avgPayCell.style.textAlign = 'center'; // 居中对齐
                avgRow.appendChild(avgPayCell);

                const avgIncomeCell = document.createElement('td');
                avgIncomeCell.textContent = (totalIncome / rowsLength).toFixed(2);;
                avgIncomeCell.style.textAlign = 'center'; // 居中对齐
                avgRow.appendChild(avgIncomeCell);

                const avgIgnoreCell = document.createElement('td');
                avgIgnoreCell.textContent = (totalIgnore / rowsLength).toFixed(2);;
                avgIgnoreCell.style.textAlign = 'center'; // 居中对齐
                avgRow.appendChild(avgIgnoreCell);

                const avgBalanceCell = document.createElement('td');
                avgBalanceCell.textContent = (totalBalance / rowsLength).toFixed(2);;
                avgBalanceCell.style.textAlign = 'center'; // 居中对齐
                avgRow.appendChild(avgBalanceCell);

                // 将平均值行添加到表格中
                tbody.appendChild(avgRow);
            }

        },
        error: function(xhr, status, error) {
            console.error('Error fetching bill data:', error);
        }
    });

    // 等待文档加载完成后执行
    document.addEventListener("DOMContentLoaded", function() {
        // 获取所有的 <tr> 行（假设表格已经渲染完毕）
        const rows = document.querySelectorAll('tr');  // 选择所有的 <tr> 元素

        // 遍历每一行
        rows.forEach(row => {
            // 检查该行是否包含 classTypeName 这一单元格，如果没有则跳过
            if (!row.querySelector('#classTypeName')) return;

            // 获取当前行中的 classTypeName 单元格
            const classTypeCell = row.querySelector('#classTypeName');

            if (classTypeCell) {
                // 获取单元格的文本内容并去除两端空白字符
                const classType = classTypeCell.innerText.trim();
                // 根据 classType 的值调用字典函数，获取对应的标签
                let badgeHtml = $.table.selectDictLabel(classTypeDatas,classType);

                // 将单元格的内容替换为相应的徽章（badge）
                classTypeCell.innerHTML = badgeHtml;
            }
        });
    });

</script>

</body>
</html>
